//创新创效 发表页面
import React, {} from 'react';
import ReactNative, {
  TextInput,
  Alert,
  Switch,
  View,
  Text,
  StyleSheet,
  Platform,
  PermissionsAndroid,
  TouchableOpacity,
  ScrollView,
  Picker,
  Image,
  Keyboard,
  ProgressViewIOS,
} from 'react-native';

import Config from '../../config';
import TImageUpLoadMultiComponent from '../../components/TImageUpLoadMultiComponent';
import CommonMaskView from '../common/CommonMaskView';
import WH_BasePage from './WH_BasePage';
import WH_Constants from './WH_Constants';
import SizeUtils from '../../common/SizeUtils';
import Constants from '../../common/Constants';
import CommonStyles from '../../common/CommonStyles';
import ToastUtils from '../../common/ToastUtils';
import WH_CreatePostAction from '../../actions/workhard/WH_CreatePostAction';
import CommonShowPickerAction from '../../actions/common/CommonShowPickerAction';
import CommonShowViewFullScreenAction from '../../actions/common/CommonShowViewFullScreenAction';

const CONTENT_MIN_HEIGHT = 144;

export default class WH_WritePage extends WH_BasePage {
  constructor(props) {
    super(props);

    this.state = {
      title: "",
      tag: 1,
      content: "",
      content1:'',
      content2:'',
      anonymous: false,
      viewStatus: 1,
      contentheight: 0,
      keyboardHeight:0,
      isUploadedImage:false, //是否已经上传完图片
      sub_tag:{value:"请选择"},
    }

    this._sendRequest = false;
    this._imageComponent = null;

    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));
    this.tagArr = [];
    if(!(Platform.OS === "ios")){
       this.state.sub_tag = WH_Constants.SUB_NEWTAG[0];
    }

    for (var i = 0; i < WH_Constants.SUB_NEWTAG.length; i++) {
      this.tagArr.push(WH_Constants.SUB_TAG[i].value);
    }
  }

  _dealLeavePage() {
    this.setState({
      viewStatus:1,
      isUploadedImage:false,
    })
    if(this._imageComponent) {
      this._imageComponent.reset();
    }
  }

  componentWillUnmount() {
    this.keyboardDidShowListener.remove();
    this.keyboardDidHideListener.remove();
  }

  componentWillUpdate(nextProps, nextStates) {
    if(nextStates.viewStatus == 3 && this._sendRequest) {
      new CommonShowViewFullScreenAction().call(this, null);
      this._resetState();
      this._sendRequest = false;
      Alert.alert('提示','发表成功，等待审核',[
          {text:'确定',onPress:()=>{this.goBack()}}
        ])
    }
    else if(nextStates.viewStatus == 4 && this._sendRequest) {
      this._sendRequest = false;
      nextStates.viewStatus = 1;
      Alert.alert('提示','发表失败',[
          {text:'确定'}
        ])
    }
    return true;
  }

  render() {
    let scrollViewHeight = SizeUtils.translateDesignHeightToCode(1100);
    // if(this.state.contentheight > CONTENT_MIN_HEIGHT) {
    //   scrollViewHeight += this.state.contentheight - CONTENT_MIN_HEIGHT;
    // }
    return(
      <View style={{paddingTop: Config.paddingTop, backgroundColor:"#ffffff"}}>
        <ScrollView style={{flexDirection:"column", height:SizeUtils.getWindowSize().height - Config.paddingTop}}
            ref={(ref) => {this._scrollView = ref}}
            keyboardShouldPersistTaps={"never"}>
          <View style={{height:scrollViewHeight,}}>
            {this._renderView()}
          </View>
          <View style={{width:SizeUtils.getWindowSize().width, height:this.state.keyboardHeight,}}>
          </View>
        </ScrollView>
        {this._renderNavigationBar()}
      </View>
    )
  }

  _keyboardDidShow(e){
    if(e.endCoordinates){
         this.setState({
          keyboardHeight:e.endCoordinates.height,
      }, ()=> {
        if (this._titleRef&&this._titleRef.isFocused()) {
          this._scrollView.scrollTo({y:0});
        }else{
          this._scrollToEnd();
        }
      })
    }else if(e.startCoordinates){
        this.setState({
          keyboardHeight:e.startCoordinates.height,
      }, ()=> {
        this._scrollToEnd();
      })
    }
  }

  _keyboardDidHide(e){
      this.setState({
          keyboardHeight:0
      }, ()=> {
        setTimeout(()=>{
          this._scrollView.scrollTo({y:0});
        }, 500);
      })
  }

  _scrollToEnd() {
    if (this.refs.contentRef&&this.refs.contentRef.isFocused()) {
      setTimeout(()=>{
        this._scrollView.scrollTo({y:80});
      }, 100);
    }else{
      setTimeout(()=>{
        this._scrollView.scrollToEnd();
      }, 100);
    }
  }

  _resetState() {
    this.setState({
      title: "",
      content: "",
      content1:'',
      sub_tag:{value:"请选择"},
      content2:'',
      anonymous: false,
      avatar: null,
    })
  }

  _renderView() {
    // if(this.state.viewStatus == 1) {
      return (
        <View style={{
          marginLeft: SizeUtils.translateDesignWidthToCode(20),
          marginRight: SizeUtils.translateDesignWidthToCode(20),}}>
          {this._renderTitleView()}
          {this._renderTypes()}
          {this._renderContent()}
          {this._renderContent1()}
          {this._renderContent2()}
          {this._renderImageUploadView()}
          {/* {this._renderSecretView()} */}
          {this._renderStatusText()}
        </View>
      )
  }

  _renderTitleView() {
    return(
      <View style={{height: SizeUtils.translateDesignHeightToCode(100), borderColor: '#eeeeee',
        flexDirection:'row',alignItems: 'center',
        width:SizeUtils.getWindowSize().width-20,
        borderBottomWidth: SizeUtils.translateDesignNumToCode(3), justifyContent:"center",}}>
        <Text style={{fontSize:SizeUtils.translateFontSizeToCode(32)}}>
            标题:关于
          </Text>
        <TextInput
          style={{
            flex:1,
            paddingLeft:5,
            paddingRight:5,
            height: SizeUtils.translateDesignHeightToCode(70),
            lineHeight:SizeUtils.translateDesignHeightToCode(70),
            marginTop:SizeUtils.translateDesignHeightToCode(15),
            fontSize: SizeUtils.translateFontSizeToCode(36)}}
          onChangeText = {(title) => this.setState({title})}
          placeholder = "1-18字"
          underlineColorAndroid="transparent"
          multiline = {false}
          maxLength={18}
          value = {this.state.title}
          ref={(ref) => this._titleRef = ref}
        //  onFocus = {this._scrollViewTo.bind(this)}
        />
        <Text style={{fontSize:SizeUtils.translateFontSizeToCode(32)}}>
            的建议
          </Text>
      </View>
    )
  }

  _renderContent() {
    return(
      <View style={{paddingTop: SizeUtils.translateDesignHeightToCode(20),borderColor: '#eeeeee', borderBottomWidth: 1,}}>
        <Text style={{fontSize:SizeUtils.translateFontSizeToCode(32)}}>问题的提出:</Text>
        <TextInput
          style={{padding:0,height: SizeUtils.translateDesignHeightToCode(CONTENT_MIN_HEIGHT),
            textAlignVertical: "top", fontSize: SizeUtils.translateFontSizeToCode(30)}}
          onChangeText = {(content) => this.setState({content:content})}
          placeholder = "请输入正文(10-700个字)"
          multiline = {true}
          underlineColorAndroid="transparent"
          value = {this.state.content}
          ref = 'contentRef'
          maxLength={700}
          onFocus = {this._scrollViewTo.bind(this)}
        />
      </View>
    )
  }
  _renderContent1() {
    return(
      <View style={{paddingTop: SizeUtils.translateDesignHeightToCode(20),borderColor: '#eeeeee', borderBottomWidth: 1,}}>
        <Text style={{fontSize:SizeUtils.translateFontSizeToCode(32)}}>解决办法:</Text>
        <TextInput
          style={{padding:0,height: SizeUtils.translateDesignHeightToCode(CONTENT_MIN_HEIGHT),
            textAlignVertical: "top", fontSize: SizeUtils.translateFontSizeToCode(30)}}
          onChangeText = {(content) => this.setState({content1:content})}
          placeholder = "请输入正文(10-700个字)"
          multiline = {true}
          underlineColorAndroid="transparent"
          value = {this.state.content1}
          ref = 'contentRef1'
          maxLength={700}
          onFocus = {this._scrollViewTo.bind(this)}
        />
      </View>
    )
  }
  _renderContent2() {
    return(
      <View style={{paddingTop: SizeUtils.translateDesignHeightToCode(20),borderColor: '#eeeeee', borderBottomWidth: 1,}}>
        <Text style={{fontSize:SizeUtils.translateFontSizeToCode(32)}}>可预见的效果:</Text>
        <TextInput
          style={{padding:0,height: SizeUtils.translateDesignHeightToCode(CONTENT_MIN_HEIGHT),
            textAlignVertical: "top", fontSize: SizeUtils.translateFontSizeToCode(30)}}
          onChangeText = {(content) => this.setState({content2:content})}
          placeholder = "请输入正文(10-700个字)"
          multiline = {true}
          underlineColorAndroid="transparent"
          value = {this.state.content2}
          ref = 'contentRef2'
          maxLength={700}
          onFocus = {this._scrollViewTo.bind(this)}
        />
      </View>
    )
  }

  //选择分类
  _renderTypes() {
     if(Platform.OS === "ios"){
       return  (<TouchableOpacity style={{height:SizeUtils.translateDesignHeightToCode(100), justifyContent:"center",
          borderColor: '#eeeeee',
          borderBottomWidth: SizeUtils.translateDesignNumToCode(3),}}
            onPress={this._onPressChooseType.bind(this)}>

          <Text style={{fontSize:SizeUtils.translateFontSizeToCode(32)}}>
            分类:  {this.state.sub_tag.value}
          </Text>
        </TouchableOpacity>)
    }
    else{
       return (
       <View style={{height:SizeUtils.translateDesignHeightToCode(130),
        borderColor: '#eeeeee',flexDirection:"row",alignItems:"center",
        borderBottomWidth: SizeUtils.translateDesignNumToCode(3),}}>
        <Text style={{textAlign:"center",alignItems:"center",fontSize:SizeUtils.translateFontSizeToCode(32)}}>
          分类:
        </Text>
        <View style={{width:SizeUtils.translateDesignWidthToCode(300)}}>
       <Picker
            style={{backgroundColor:"#ffffff00"}}
            selectedValue={this.state.sub_tag.value}
            mode="dialog"
            prompt={'请选择'}
            onValueChange={(value) => this._onPickerCallback(value)}>
            {this.tagArr.map((item, index) =>
              {return(
                <Picker.Item
                style={{fontSize:SizeUtils.translateFontSizeToCode(32),color:'#eeeeee'}}
                  key={index}
                  value={item}
                  label={item}
                />
              )}
            )}

          </Picker></View></View>)
        }

  }


  _onPressChooseType() {
    let tagArr = [];
    for (var i = 0; i < WH_Constants.SUB_NEWTAG.length; i++) {
      tagArr.push(WH_Constants.SUB_NEWTAG[i].value);
    }
    new CommonShowPickerAction().call(this, {pickerData:tagArr,
      callback:this._onPickerCallback.bind(this)});
  }

  _onPickerCallback(selectedValue) {
    let selectedData = [];
    for (var i = 0; i < WH_Constants.SUB_NEWTAG.length; i++) {
      if(selectedValue == WH_Constants.SUB_NEWTAG[i].value) {
        selectedData = WH_Constants.SUB_NEWTAG[i];
        break;
      }
    }
    this.setState({
      sub_tag:selectedData,
    });
  }

  _renderImageUploadView() {
    let width = SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(80);
    let height = SizeUtils.translateDesignWidthToCode(160);
    return(
      <TImageUpLoadMultiComponent
        ref={(ref) => this._imageComponent = ref}
        style={{width:width,
            height:height, marginTop:SizeUtils.translateDesignHeightToCode(20)}}
        containerStyle={{width:width,
          height:height}}
        imageStyle={{width:160, height:160}} maxCount = {3}
        />
    )
  }

  _renderSecretView() {
    return(
      <View style={{marginTop: SizeUtils.translateDesignHeightToCode(30),
          flexDirection:"row", alignItems:"center"}}>
        <Text style={[CommonStyles.secondaryText, {fontSize:SizeUtils.translateFontSizeToCode(30)}]}>
          匿名发布
        </Text>
        <Switch value={this.state.anonymous} onValueChange={() => this.setState({anonymous:!this.state.anonymous})}
          style={{marginLeft:SizeUtils.translateDesignWidthToCode(24)}}/>
      </View>
    )
  }

  _scrollViewTo(e){
    // let target = e.nativeEvent.target;
    // let scrollLength = 200;
    // if (target === ReactNative.findNodeHandle(this.refs.contentRef)) {
    //   scrollLength = 300;
    // }
    // this._scrollView.scrollTo(SizeUtils.translateDesignHeightToCode(scrollLength));
　}

  _onContentSizeChange(event) {
    this.setState({contentheight: event.nativeEvent.contentSize.height + SizeUtils.translateDesignHeightToCode(80)}, ()=> {
      this._scrollToEnd();
    });
  }

  _renderStatusText() {
    if(this.state.viewStatus == 2 || this.state.viewStatus == 5) {
      let text = "";
      if(this.state.viewStatus == 2) {
        text = "发表中(上传文本)...";
      }
      else if(this.state.viewStatus == 5) {
        if(this.state.isUploadedImage == true) {
          text = "发表中...";
        }
        else {
          text = "发表中(上传图片)...";
        }
      }
      return (
        <View style={{paddingTop:SizeUtils.translateDesignHeightToCode(40)}}>
          <Text>{text}</Text>
        </View>
      )
    }
  }

  _onPressNavigationBarRightBtn() {
    if(this.state.title === ""){
       ToastUtils.show("请输入标题");
    }
    else if(this.state.sub_tag.value === "请选择"){
       ToastUtils.show("请选择分类");
    }
    // else if(!this.avatarData || this.state.avatar == null){
    //    ToastUtils.show("请上传图片");
    // }
    else if(this.state.content === "" || this._strlen(this.state.content) < 10){
       ToastUtils.show("请输入问题的提出(10-700个字)");
    }
    else if(this.state.content1 === "" || this._strlen(this.state.content1) < 10){
       ToastUtils.show("请输入解决方法(10-700个字)");
    }
    else if(this.state.content2 === "" || this._strlen(this.state.content2) < 10){
       ToastUtils.show("请输入可预见效果(10-700个字)");
    }
    else if(this.state.viewStatus == 1) {
      if(this.avatarData === null){
        this._callWH_CreatePostAction()
        return;
      }
      this.setState({
        viewStatus:5,
      })
      new CommonShowViewFullScreenAction().call(this, {component:CommonMaskView})
      this._imageComponent.doUpload(this._onUploadCallback.bind(this));
    }
  }

  _onUploadCallback(imageUrls) {
    this._callWH_CreatePostAction(imageUrls);
    this.setState({
      isUploadedImage:true,
    })
  }

  _callWH_CreatePostAction(imageUrls) {
     if(this._sendRequest){
      return;
    }
    new WH_CreatePostAction().call(this, {content:this.state.content+'&'+this.state.content1+'&'+this.state.content2,
      tag:this.state.tag,
      sub_tag:this.state.sub_tag.key,
      title:'关于'+this.state.title+'的建议',
      image_urls:imageUrls,
      anonymous:this.state.anonymous ? 1 : 0});
    this._sendRequest = true;
  }

  _strlen(str){
    var len = 0;
    for (var i=0; i<str.length; i++) {
     var c = str.charCodeAt(i);
    //单字节加1
     if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {
       len++;
     }
     else {
      len+=2;
     }
    }
    return len;
  }
}
